package cn.itsource.ymcc.producer;

import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.constant.OrderStatusConstants;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.dto.PayOrderDto;
import cn.itsource.ymcc.mapper.CourseOrderMapper;
import cn.itsource.ymcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@RocketMQTransactionListener(
        txProducerGroup = OrderStatusConstants.MQ_COURSEORDER_PAY_GROUP_TRANSACTION
)
@Component
public class CourseOrderTransactionListener implements RocketMQLocalTransactionListener {
    @Autowired
    private ICourseOrderService iCourseOrderService;
    //执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
            if(message == null || message.getPayload() == null || o == null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            //本地事务是要执行的东西
            iCourseOrderService.saveTransactionCourseOrder((CourseOrder) o);
            return RocketMQLocalTransactionState.COMMIT;
    }

    //检查本地事务
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] by =  (byte[])message.getPayload();
            String s = new String(by, Constants.UTF8);
            PayOrderDto p = JSON.parseObject(s,PayOrderDto.class);
            CourseOrder order_no = iCourseOrderService.getOne(new QueryWrapper<CourseOrder>().eq("order_no", p.getOrderNo()));
            if(order_no == null){
               return RocketMQLocalTransactionState.ROLLBACK;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
